<template>
  <div>
    <div class="list">
      <div
        class="item"
        v-for="item of letters"
        :key="item"
        :ref="item"
        @click="commit"
        @touchstart="touchstart"
        @touchmove="touchmove"
        @touchend="touchend"
      >
        {{ item }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "CityAlphabet",
  props: {
    cities: Object,
  },
  data() {
    return {
      touchStatus: false,
      startY: 0,
      timer: null,
    };
  },
  updated() {
    this.startY = this.$refs["A"][0].offsetTop;
  },
  methods: {
    commit(e) {
      //   console.log(e.target.innerText);
      this.$emit("change", e.target.innerText);
    },
    touchstart() {
      this.touchStatus = true;
    },
    touchmove(e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY - 104;
          const index = Math.floor((touchY - this.startY) / 20);
          if (0 <= index < this.letters.length) {
            this.$emit("change", this.letters[index]);
          }
        }, 16);
      }
    },
    touchend() {
      this.touchStatus = false;
    },
  },
  computed: {
    letters() {
      const letters = [];
      for (let i in this.cities) {
        letters.push(i);
      }
      return letters;
    },
  },
};
</script>

<style scoped>
.list {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: absolute;
  justify-content: center;
  top: 2.1rem;
  right: 0;
  bottom: 0;
  width: 0.4rem;
  border-radius: 0.2rem;
}
.item {
  width: 0.4rem;
  line-height: 0.4rem;
  text-align: center;
  color: rgb(39, 202, 161);
}
</style>